package com.ktjy.springsecuritydemo.config;
import com.ktjy.springsecuritydemo.handle.MyAccessDeniedHandler;
import com.ktjy.springsecuritydemo.service.UserDetailsServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Resource
    private UserDetailsServiceImpl userDetailsServiceImpl;
    @Resource
    private DataSource dataSource;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, UserDetailsServiceImpl userDetailsService) throws Exception{
        //表单提交
        http.formLogin(formLoginSpec -> formLoginSpec
                .usernameParameter("user")
                .passwordParameter("pwd")
                .loginPage("/toLogin")
                .loginProcessingUrl("/doLogin")
                .successForwardUrl("/toMain")
                .failureForwardUrl("/toError")
//                .failureHandler(new MyAuthenticationFailureHandler("/toError"))
                .permitAll());

        http.authorizeHttpRequests((authz) -> authz.
                requestMatchers("/toLogin").permitAll()
                .requestMatchers("/doLogin").permitAll()
               .requestMatchers("/toMain").permitAll()
                .requestMatchers("/toError").permitAll()
                .requestMatchers("/css/**","/js/**","/images/**").permitAll()
//              .requestMatchers("/toMain1")
//              .requestMatchers("/toMain1").access(new WebExpressionAuthorizationManager("isAuthenticated() and hasIpAddress('127.0.0.1')"))
                .anyRequest().authenticated()
        ).httpBasic(withDefaults());

        http.exceptionHandling((ex)->ex.accessDeniedHandler(myAccessDeniedHandler));

        http.rememberMe((me)->me.userDetailsService(userDetailsServiceImpl).tokenRepository(getPersistentTokenRepository()));

        http.logout((out)->out.logoutSuccessUrl("/toLogin"));
        //关闭csrf防火墙
        http.csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }
    @Bean
    public PersistentTokenRepository getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
}
